/* drift class */

class DriftPlotter {
public:
  string name;
  string datafile;
  string plotcmd;
  Piper  plotpipe;
  Buffer plotdata;
  int slab;
  char axis;
  enum {contour, point} plottype;
  
  DriftPlotter(string pname, Buffer& buf) {
    name=pname;
    plotdata.refto(&buf);
    datafile="xxx-plotdata-"+name+"-xxx";
    plotpipe.open("gnuplot > /dev/null 2>&1");
    init_slab(0,'z');
  }
  
  ~DriftPlotter() {
    system((string("rm -f ")+datafile).c_str());
  }
  
  void init_slab(int s, const char norm) {
    plottype=contour;
    axis=norm;
    slab=s;
    plotpipe.send("reset\nset term x11");
    plotpipe.send("set pm3d\nunset surface\nset contour\nset view map");
    plotpipe.send("set key left outside");
    plotcmd="sp '"+datafile+"' matrix w l not";
  }
  
  void init_prof(const char ax) {
    plottype=point;
    axis=ax;
    plotpipe.send("reset \nset term x11");
    plotpipe.send("set key left outside");
    plotcmd="p '"+datafile+"' u 1:2 not";
  }
  
  void send(string cmd) {plotpipe.send(cmd);}
  
  void snap(string snapfile) {
    send("set term png");
    send("set output '"+snapfile+".png");
    plot();
    send("set term x11");
  }                                                      
  
  void save(string fname) {
    if(file_exist(datafile)) {
      
      string cmd("cp ");
      cmd.append(datafile+" "+fname);
      system(cmd.c_str());
      
      cmd=datafile;
      datafile=fname;
      plot();
      datafile=cmd;

      cmd="save '";
      cmd.append(fname+".plot'");
      send(cmd);
      
    }
  }
  
  void plot_contour() {
    ofstream ofl(datafile.c_str());
    plotdata.dump(ofl,slab,axis);
    ofl.flush();
    ofl.close();
    send("set title 'slab="+as_string(slab)+"'");
    if(axis=='z') send("set xlabel 'x'\nset ylabel 'y'");
    if(axis=='y') send("set xlabel 'x'\nset ylabel 'z'");
    if(axis=='x') send("set xlabel 'y'\nset ylabel 'z'");
    send(plotcmd);      
  }
  
  void plot_point() {
    ofstream ofl(datafile.c_str());
    plotdata.dump(ofl,axis);
    ofl.flush();
    ofl.close();
    char c[2]={axis,0x0};
    send("set xlabel '"+string(c)+"'");
    send(plotcmd);
  }

  void plot() {
    if(plottype==contour) plot_contour();
    if(plottype==point) plot_point();
  }  

};
